/**
 * 
 */
package com.feib.soeasy.job.service.impl;

import java.io.File;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.enterprisedt.net.ftp.FileTransferClient;
import com.feib.soeasy.dao.Bp004Dao;
import com.feib.soeasy.dao.CodeTableDao;
import com.feib.soeasy.dao.GroupDao;
import com.feib.soeasy.dao.MailQueueDao;
import com.feib.soeasy.dao.UploadFileDao;
import com.feib.soeasy.job.service.AutoUploadCarLoanFileService;
import com.feib.soeasy.model.CodeTable;
import com.feib.soeasy.model.Group;
import com.feib.soeasy.model.MailQueue;
import com.feib.soeasy.model.UploadFile;

/**
 * @author Jimmy Liu
 *
 */
@Service("autoUploadCarLoanFileService")
public class AutoUploadCarLoanFileServiceImpl implements
AutoUploadCarLoanFileService {

	protected Logger logger = LoggerFactory.getLogger(this.getClass());

	@Resource(name="codeTableDao")
	private CodeTableDao codeTableDao;	

	@Resource(name="groupDao")
	private GroupDao groupDao;

	@Resource(name="uploadFileDao")
	private UploadFileDao uploadFileDao;

	@Resource(name="mailQueueDao")
	private MailQueueDao mailQueueDao;

	@Resource(name="bp004Dao")
	private Bp004Dao bp004Dao;

	/* (non-Javadoc)
	 * @see com.feib.soeasy.job.service.AutoUploadCarLoanFileService#updateRunDate(com.feib.soeasy.model.CodeTable)
	 */
	@Override
	public void updateRunDate(CodeTable runDate) {
		this.codeTableDao.save(runDate);

	}

	/* (non-Javadoc)
	 * @see com.feib.soeasy.job.service.AutoUploadCarLoanFileService#findCodeTables(java.lang.String)
	 */
	@Override
	@Deprecated
	public List<CodeTable> findCodeTables(String codeKind) {
		return codeTableDao.findByCodeKind(codeKind);
	}

	/* (non-Javadoc)
	 * @see com.feib.soeasy.job.service.AutoUploadCarLoanFileService#getCodeTable(java.lang.String, java.lang.String)
	 */
	@Override
	public CodeTable getCodeTable(String codeKind, String codeValue) {
		return codeTableDao.getCodeTable(codeKind, codeValue);
	}

	/**
	 * 
	 * @param host FTP SERVER IP
	 * @param port FTP SERVER PORT
	 * @param username FTP 帳號
	 * @param password FTP 密碼
	 * @param localFolder 本地端目錄/下載存放目錄
	 * @param remoteFolder FTP 目錄
	 * @param sFileName 檔案名稱
	 * @param iRetryCnt FTP Retry 次數/下載嘗試數次
	 * @return
	 */
	public boolean retryGetFtpFile(String host, int port, String username, String password
			, String localFolder, String remoteFolder
			,String sFileName, int iRetryCnt)
	{
		boolean bRtn = false;
		for (int i=1; i<=iRetryCnt; i++){
			bRtn = getFTPFile(host, port, username, password, localFolder, remoteFolder, sFileName, i);
			if (bRtn){
				/* 成功下載 */                              
				break;
			}       
		}   
		if (!bRtn){
			/* 超過Retry上限  */
			logger.error("Retry FTP Get File Fail..");
		}                       
		return bRtn;
	}

	/* 取得FTP檔案 FTP Server */
	public boolean getFTPFile(String host, int port, String username, String password
			, String localFolder, String remoteFolder
			,String sFileName, int iRetry) {


		FileTransferClient ftp = null;

		try {
			logger.info("FTP Server Connect : {}", host);
			logger.info("FTP User Name : {}", username);
			logger.info("FTP Local Directory : {}", localFolder);
			logger.info("FTP Remote Directory : {}", remoteFolder);
			logger.info("FTP Retry Times : {}", iRetry);

			/* Free Java FTP library edtFTPj http://www.enterprisedt.com/index.html */
			ftp = new FileTransferClient();
			ftp.setRemoteHost(host);
			ftp.setRemotePort(port);
			ftp.setUserName(username);
			ftp.setPassword(password); 
			ftp.connect();
			if (ftp.isConnected()){
				logger.info("FTP File = {}", sFileName.toUpperCase());
				/* 刪除舊檔案 */
				File uploadedFile = new File(localFolder + "\\" + sFileName);
				if(uploadedFile.exists()){
					uploadedFile.delete();
					logger.info("Delete {}/{}", localFolder, sFileName);
				}
				/* 切換FTP目錄  */
				if (remoteFolder != null && !remoteFolder.trim().equals("")){
					ftp.changeDirectory(remoteFolder);
					logger.info("Directory change to {}", ftp.getRemoteDirectory());
				}

				logger.info("File {} size is {} Bytes", sFileName, ftp.getSize(sFileName));
				/* 下載檔案 */
				ftp.downloadFile(localFolder, sFileName);
				/* 儲存檔案名稱 */
				logger.info("Download {} to {}", sFileName, localFolder);
			}   
			ftp.disconnect(true);
			return true;   
		} catch (Exception ex) {
			try {    
				logger.info("Disconnect ftp");
				if (null != ftp && ftp.isConnected())
					ftp.disconnect(true);

				ftp = null;
			}
			catch (Exception e) {            	
				logger.info(ex.toString(), ex);
			}
			logger.info(ex.toString(), ex);
			logger.info("Retry FTP {}", iRetry);
			return false;                                       
		}
	}

	@Override
	public boolean hasUploadFile(String groupNo, String fileName) {

		Group group = groupDao.findByGroupNo(groupNo);

		@SuppressWarnings("unchecked")
		List<UploadFile> list = uploadFileDao.findUploadFileByFileName(group, fileName);

		if (null == list || 0 == list.size())
			return false;

		for (UploadFile u: list)
		{
			Integer status = u.getFileStatus();
			if (null != status)
			{				
				if (UploadFile.FILE_STATUS_CONFIRM_OK.equals(status)
						|| UploadFile.FILE_STATUS_WAITING_CONFIRM.equals(status)
						|| UploadFile.FILE_STATUS_CREATE_REPORT.equals(status)
						|| UploadFile.FILE_STATUS_IN_CHECKING.equals(status)
						|| UploadFile.FILE_STATUS_UN_CHECK.equals(status))
				{
					list.clear();
					list = null;

					return true;
				}
			}
		}

		list.clear();
		list = null;


		return false;
	}

	@Override
	public boolean isHoliday(Date now) {
		return bp004Dao.isHoliday(now);
	}

	@Override
	public MailQueue addMailQueue(MailQueue mailQueue) {

		mailQueue.setMailStatus(new Integer(0)); // 待發送
		mailQueue.setInQueueDate(new Date());

		return mailQueueDao.save(mailQueue);
	}

}
